//
//  NetWorkingTools.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/10.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import AFNetworking
//错误类别标记
let GFdemonName = "com.baidu.www"

//网络访问错误
private enum GFNetworkError: Int{
    case emptyDataError = -1
    case emptyTokenError = -2
    
    private var description:String {
        switch self{
        case .emptyDataError:
            return "空数据"
        case .emptyTokenError:
            return "Accestoken 为空"
        }
        
    }
    private var error: NSError{
        return NSError(domain: GFdemonName, code: rawValue, userInfo:[GFdemonName:description])
    }
}
//网络访问方法
private enum GFNetworkMethok:String{
    case GET = "GET"
    case POST = "POST"
}

class NetWorkingTools: AFHTTPSessionManager {
    //网络类型别名
    typealias GFNetFinishedCallBack = (result: [String:AnyObject]?,error:NSError?)->()
    
    //单例
    static let sharedTools:NetWorkingTools = {
        let urlstring = NSURL(string: "https://api.weibo.com/")!
        let tools = NetWorkingTools(baseURL: urlstring)
        
        //设置数据解析类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
    }()
    
    //检查并且生成token字典
    private func tokenDict(finished:GFNetFinishedCallBack)-> [String:AnyObject]? {
        
        //首先判断token是否存在
        if UserAccount.shareAccount?.access_token == nil{
            
            let error = GFNetworkError.emptyTokenError.error
            print(error)
            finished(result: nil, error: error)
            
            return  nil
        }
        //生成字典返回
        return ["access_token":UserAccount.shareAccount!.access_token!]
    }
    
    //MARK- 发布微博
    func sendStatus(status:String,image:UIImage?, finished:GFNetFinishedCallBack) {
        
        guard var params = tokenDict(finished) else {
//          pargram为nil，直接返回
            return
        }
        params["status"] = status

        //POST发布微博
        if image == nil {
            
            //判断，有没有图片，没有就发布文本微博
        requese(GFNetworkMethok.POST, urlstring: "2/statuses/update.json", params: params, finished: finished)
            
        }else {
            
            //发布图片微博
            uploadImage("https://upload.api.weibo.com/2/statuses/upload.json", image: image!, params: params, finished: finished)
        }
    }

    //MARK- 加载微博信息
    func loadStatus(sinct_id:Int,max_id:Int,finished: GFNetFinishedCallBack){
        //首先判断token是否存在
        guard var pargram = tokenDict(finished) else {
//          pargram为nil，直接返回
            return
        }
        if sinct_id > 0 {
            pargram["sinct_id"] = sinct_id
        }
        if max_id > 0 {
            pargram["max_id"] = max_id - 1
        }

        let urlstring = "2/statuses/home_timeline.json"

        //发送请求
        requese(GFNetworkMethok.GET, urlstring: urlstring, params: pargram, finished: finished)
    }
    
    //加载用户数据  此处加载微博数据
    func loadUserInfo(uid:String,finshed:GFNetFinishedCallBack){

        guard var pargram = tokenDict(finshed) else {
            return
        }
        
        //代码运行至此，肯定有值
        let urlstring = "2/users/show.json"
        pargram["uid"] = uid

        //发送网络请求
        requese(GFNetworkMethok.GET, urlstring: urlstring, params: pargram, finished: finshed)

    }
    //    OAtuth授权
    private let clientId = "167401659"
    private let appSecret = "8170e7a2c511e8932f2fac7b10222317"
    //回调地址
    let redirectUrl = "http://www.baidu.com"
    
    //获取OAuth授权页面
    func oauthUrl()->NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUrl)"
      
        return NSURL(string: urlString)!
    }

//    加载token
    func loadAccessToken(code:String,finished:(GFNetFinishedCallBack)) {
        
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        let pargram = ["client_id":clientId,
        "client_secret":appSecret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirectUrl]
      
        POST(urlstring, parameters: pargram, success: { (_, JSON) -> Void in
            finished(result: JSON as?[String:AnyObject], error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
    
    //1 定义成功的闭包
    private func requese(methos:GFNetworkMethok, urlstring:String,params:[String:AnyObject],finished:GFNetFinishedCallBack){
        
        let successCallBack: (NSURLSessionDataTask!,AnyObject!)-> Void =
        { (_,JSON) -> Void in
            
            if let result = JSON as?[String:AnyObject]{
                
                //有结果的回调
                finished(result: result, error: nil)
                
            }else{
                //么有错误，同样没有结果
                print("没有数据\(methos) Request \(urlstring)")
                
            }
        }
        //2 定义失败的闭包
        let failedCallBack:(NSURLSessionDataTask!,NSError!) -> Void =
        {(_,error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
//        3,根据methok来选择执行的方法
        switch methos {
        case .GET:
            GET(urlstring, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlstring, parameters: params, success: successCallBack, failure: failedCallBack)
        }
   
    }
    
    private func uploadImage(urlString:String,image:UIImage,params:[String:AnyObject],finished:GFNetFinishedCallBack){
   
        //成功闭包
        let successCallBack: (NSURLSessionDataTask!,AnyObject!)-> Void =
        { (_,JSON) -> Void in
            
            if let result = JSON as?[String:AnyObject]{
                
                //有结果的回调
                finished(result: result, error: nil)
                
            }else{
                //么有错误，同样没有结果
                print("没有数据\(urlString)")
                finished(result: nil, error: GFNetworkError.emptyDataError.error)
            }
        }
        
        //2 定义失败的闭包
        let failedCallBack:(NSURLSessionDataTask!,NSError!) -> Void =
        {(_,error) -> Void in
            print(error)
            
            finished(result: nil, error: error)

            }
        POST(urlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
  
            let data = UIImagePNGRepresentation(image)!
            
                //构造函数
               formData.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "application/octet-stream")
            
            }, success: successCallBack, failure: failedCallBack)
        
        }
    
    }
    

